<template>
  <div>
    <Breadcrumb :opt-data="projectOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="projectData"
          :custom-empty="true"
          @pageChanged="getProjectData"
          @sizeChanged="getProjectData"
          @filterChange="getProjectData">
          <EmptyContent slot="empty" :opt-data="projectOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditProject ? '新增' : '编辑'}项目`"
        :close-on-click-modal="false"
        :visible.sync="showProjectDialog"
        width="600px"
        center>
        <el-form
          v-loading="projectFormLoading"
          :ref="projectFormRef"
          :model="projectForm"
          :rules="projectFormRules"
          size="small"
          label-width="130px">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="projectForm.name" placeholder="请填写项目名称"></el-input>
          </el-form-item>
          <el-form-item label="项目地点" prop="address">
            <el-input v-model="projectForm.address" placeholder="请填写项目地点"></el-input>
          </el-form-item>
          <el-form-item label="会议室数量" prop="roomNumber">
            <el-input-number :min="0" v-model="projectForm.roomNumber" placeholder="请填写会议室数量" controls-position="right" class="width-100"></el-input-number>
          </el-form-item>
          <el-form-item label="项目类别" prop="type">
            <el-input v-model="projectForm.type" placeholder="请填写项目类别"></el-input>
          </el-form-item>
          <el-form-item label="项目成员" prop="members">
            <el-select class="width-100" v-model="projectForm.members" filterable multiple collapse-tags placeholder="请选择项目成员">
              <el-option
                v-for="item in userData"
                :key="item._id"
                :label="item.name + ' - ' + item.username"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="projectForm.description" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="projectFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="projectFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {msgCode} from "@/config/string";
  import {confirmHandle, deepCopyWithJson, getUserInfo, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import projectTableCfg from "@/config/table/project";
  import EZTable from '@/components/table/EZTable';
  import {routerMeta} from "@/router/routerMeta";
  import Upload from '@/components/ImageUpload.vue';

  export default {
    name: "ProjectManagement",
    components: {
      EZTable, Upload
    },
    data() {
      return {
        tableLoading: true,
        tableId: tableIdConfig.project,
        tableHdl: null,
        projectData: [],
        showProjectDialog: false,
        projectFormLoading: false,
        projectForm: {},
        projectFormRules: {
          name: [
            {required: true, message: '请填写项目名称', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '请填写项目地点', trigger: 'blur'}
          ],
          roomNumber: [
            {required: true, message: '请填写会议室数量', trigger: 'blur'}
          ],
        },
        projectFormRef: 'projectFormRef',
        isEditProject: false,
        userData: [],
        role: getUserInfo().role,
      }
    },
    computed: {
      projectOptData() {
        return [
          {
            type: 'btn',
            label: '公共图片管理',
            icon: 'icon-upload',
            hide:this.role==='guest',
            callback: () => {
	            this.$router.push({name: routerMeta.commonAsset.name});
            }
          },
          {
            type: 'btn',
            label: '新增项目',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initProjectForm();
      this.getProjectData();
      this.getUserData();
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, projectTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const project = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.roomComponent.type:
              this.$router.push({
                name: routerMeta.projectRoom.name,
                params: {pid: data._id},
                query: {subTitle: data.name}
              });
              break;
            case tableOptBtnConfig.edit.type:
              this.showProjectDialog = true;
              this.isEditProject = true;
              this.projectForm = project;
              this.projectForm.members = project.members.map(ele => ele.userId);
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteProject(project);
              break;
            case tableOptBtnConfig.assetManage.type:
	            this.$router.push({name: routerMeta.projectAsset.name, params: {pid: data._id}});
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initProjectForm() {
        this.projectForm = {
          name: '',
          type: '',
          description: '',
          address:'',
          roomNumber:0
        }
      },
      resetProjectForm() {
        this.initProjectForm();
        const projectForm = this.$refs[this.projectFormRef];
        projectForm && projectForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditProject && this.resetProjectForm();
        this.showProjectDialog = true;
        this.isEditProject = false;
      },
      getProjectData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.project.projectList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.projectData = data;
          this.projectData.forEach(ele => {
            ele.memberNames = ele.members.map(item => `<span size="small" closable>${item.name}</span>`).join('、');
            ele.projectEditBtn = !ele.isShare;
          })
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      getUserData() {
        API.user.userAll().then(result => {
          const {data = []} = result;
          this.userData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      deleteProject(project = {}) {
        confirmHandle({label: `确定要删除项目：${project.name} 吗?`}).then(() => {
            API.room.roomList({selector:{projectId:project._id}}).then(result => {
              if(result.data.length===0){
              API.project.projectDelete({_id: project._id}).then(result => {
                messageHandle({code: msgCode.DELETE_SUCCESS, title: '项目'});
                this.tableHdl.judgeTableMatched();
                this.getProjectData();
                this.resetProjectForm();
              });
              }else{
                this.$notify({
                  message: '该项目下包含子房间工程，不能被删除',
                  type: 'error',
                  duration: 3000,
                });
              }
            })
        }).catch(() => {
        });
      },
      projectFormCanceled() {
        this.showProjectDialog = false;
      },
      projectFormSubmitted() {
        this.$refs[this.projectFormRef].validate((valid) => {
          if (!valid) return;
          this.projectFormLoading = true;
          if (!this.isEditProject) {
            API.project.projectAdd({...this.projectForm}).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '项目'});
              this.showProjectDialog = false;
              this.projectFormLoading = false;
              this.getProjectData();
              this.resetProjectForm();
            }).catch(err => {
              console.log('err', err);
              this.projectFormLoading = false;
            });
          } else {
            API.project.projectEdit({...this.projectForm}).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '项目'});
              this.showProjectDialog = false;
              this.projectFormLoading = false;
              this.getProjectData();
              this.resetProjectForm();
            }).catch(err => {
              console.log('err', err);
              this.projectFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
